import { Entity } from '../systems/EntitySystem.js';
import { RenderSystem } from '../systems/RenderSystem.js';
import { GameConfig } from '../config/GameConfig.js';

export enum BuildingType {
    GOVERNMENT = 'government',
    AIRPORT = 'airport',
    PORT = 'port',
    RESIDENTIAL = 'residential',
    MILITARY = 'military'
}

export interface BuildingConfig {
    name: string;
    maxHealth: number;
    icon: string;
    width: number;
    height: number;
    priority: number; // 目标优先级，数值越高优先级越高
    defensiveValue: number; // 防御价值
}

export class Building implements Entity {
    public id: string;
    public x: number;
    public y: number;
    public width: number;
    public height: number;
    public active: boolean = true;
    
    private buildingType: BuildingType;
    private config: BuildingConfig;
    private health: number;
    private maxHealth: number;
    private isDestroyed: boolean = false;
    private lastDamageTime: number = 0;
    private damageFlashTimer: number = 0;

    constructor(id: string, buildingType: BuildingType, x: number, y: number) {
        this.id = id;
        this.buildingType = buildingType;
        this.x = x;
        this.y = y;
        
        // 获取建筑物配置
        this.config = this.getBuildingConfig(buildingType);
        this.width = this.config.width;
        this.height = this.config.height;
        this.maxHealth = this.config.maxHealth;
        this.health = this.maxHealth;
    }

    private getBuildingConfig(type: BuildingType): BuildingConfig {
        const configs: Record<BuildingType, BuildingConfig> = {
            [BuildingType.GOVERNMENT]: {
                name: '政府大楼',
                maxHealth: 300,
                icon: '🏛️',
                width: 60,
                height: 80,
                priority: 10,
                defensiveValue: 1000
            },
            [BuildingType.AIRPORT]: {
                name: '机场',
                maxHealth: 250,
                icon: '✈️',
                width: 80,
                height: 60,
                priority: 8,
                defensiveValue: 800
            },
            [BuildingType.PORT]: {
                name: '港口',
                maxHealth: 200,
                icon: '🚢',
                width: 70,
                height: 50,
                priority: 6,
                defensiveValue: 600
            },
            [BuildingType.RESIDENTIAL]: {
                name: '住宅区',
                maxHealth: 150,
                icon: '🏘️',
                width: 50,
                height: 40,
                priority: 4,
                defensiveValue: 400
            },
            [BuildingType.MILITARY]: {
                name: '军事设施',
                maxHealth: 400,
                icon: '🪖',
                width: 70,
                height: 70,
                priority: 9,
                defensiveValue: 1200
            }
        };
        
        return configs[type];
    }

    update(deltaTime: number): void {
        if (!this.active) return;

        // 更新伤害闪烁效果
        if (this.damageFlashTimer > 0) {
            this.damageFlashTimer -= deltaTime;
        }

        // 检查是否被摧毁
        if (this.health <= 0 && !this.isDestroyed) {
            this.isDestroyed = true;
            this.onDestroyed();
        }
    }

    render(renderSystem: RenderSystem): void {
        if (!this.active) return;

        const healthPercent = this.health / this.maxHealth;
        
        // 根据血量确定建筑颜色
        let buildingColor = '#708090'; // 灰色（正常）
        if (healthPercent < 0.7) {
            buildingColor = '#8B4513'; // 棕色（轻微损坏）
        }
        if (healthPercent < 0.4) {
            buildingColor = '#A0522D'; // 深棕色（中度损坏）
        }
        if (healthPercent < 0.2) {
            buildingColor = '#654321'; // 暗棕色（严重损坏）
        }

        // 受伤闪烁效果
        if (this.damageFlashTimer > 0) {
            buildingColor = '#FF6B6B'; // 红色闪烁
        }

        // 渲染建筑主体
        renderSystem.renderEntity(this.x, this.y, this.width, this.height, buildingColor);
        
        // 渲染建筑边框
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        ctx.strokeStyle = '#333333';
        ctx.lineWidth = 2;
        ctx.strokeRect(
            this.x - this.width/2, 
            this.y - this.height/2, 
            this.width, 
            this.height
        );
        ctx.restore();

        // 渲染图标
        renderSystem.renderText(
            this.config.icon, 
            this.x - 10, 
            this.y - this.height/2 - 25, 
            'white', 
            '24px Arial'
        );

        // 渲染建筑名称
        renderSystem.renderText(
            this.config.name,
            this.x - this.width/2,
            this.y + this.height/2 + 15,
            'white',
            '12px Arial'
        );

        // 渲染血条
        this.renderHealthBar(renderSystem);

        // 渲染伤害数字（如果有）
        this.renderDamageNumbers(renderSystem);
    }

    private renderHealthBar(renderSystem: RenderSystem): void {
        const barWidth = this.width;
        const barHeight = 6;
        const healthPercent = this.health / this.maxHealth;
        
        // 血条背景
        renderSystem.renderEntity(
            this.x, 
            this.y - this.height/2 - 15, 
            barWidth, 
            barHeight, 
            'rgba(0, 0, 0, 0.8)'
        );
        
        // 血条边框
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1;
        ctx.strokeRect(
            this.x - barWidth/2, 
            this.y - this.height/2 - 15 - barHeight/2, 
            barWidth, 
            barHeight
        );
        ctx.restore();
        
        // 血条填充
        let healthColor = '#28a745'; // 绿色
        if (healthPercent < 0.6) healthColor = '#ffc107'; // 黄色
        if (healthPercent < 0.3) healthColor = '#dc3545'; // 红色
        
        if (healthPercent > 0) {
            renderSystem.renderEntity(
                this.x - barWidth/2 + (barWidth * healthPercent)/2,
                this.y - this.height/2 - 15,
                barWidth * healthPercent,
                barHeight,
                healthColor
            );
        }

        // 血量数字
        renderSystem.renderText(
            `${Math.ceil(this.health)}/${this.maxHealth}`,
            this.x - 20,
            this.y - this.height/2 - 30,
            'white',
            '10px Arial'
        );
    }

    private renderDamageNumbers(renderSystem: RenderSystem): void {
        // 可以在这里添加飘浮的伤害数字效果
        // 暂时留空，后续可以扩展
    }

    // 公共接口
    public takeDamage(damage: number, source?: string): boolean {
        if (this.isDestroyed) return false;

        this.health -= damage;
        this.lastDamageTime = Date.now();
        this.damageFlashTimer = 200; // 200ms 闪烁效果

        console.log(`🏢 ${this.config.name} 受到 ${damage} 点伤害，剩余血量: ${Math.max(0, this.health)}/${this.maxHealth}`);

        if (this.health <= 0) {
            this.health = 0;
            return true; // 建筑被摧毁
        }

        return false; // 建筑未被摧毁
    }

    public getHealth(): number {
        return this.health;
    }

    public getMaxHealth(): number {
        return this.maxHealth;
    }

    public getHealthPercentage(): number {
        return this.health / this.maxHealth;
    }

    public getBuildingType(): BuildingType {
        return this.buildingType;
    }

    public getBuildingName(): string {
        return this.config.name;
    }

    public getPriority(): number {
        return this.config.priority;
    }

    public getDefensiveValue(): number {
        return this.config.defensiveValue;
    }

    public isInBounds(x: number, y: number): boolean {
        return x >= this.x - this.width/2 &&
               x <= this.x + this.width/2 &&
               y >= this.y - this.height/2 &&
               y <= this.y + this.height/2;
    }

    public repair(amount: number): void {
        if (this.isDestroyed) return;
        
        this.health = Math.min(this.maxHealth, this.health + amount);
        console.log(`🔧 ${this.config.name} 修复 ${amount} 点，当前血量: ${this.health}/${this.maxHealth}`);
    }

    private onDestroyed(): void {
        console.log(`💥 ${this.config.name} 已被摧毁！`);
        // 可以触发爆炸效果、音效等
        // 暂时保持激活状态但标记为已摧毁，这样仍可显示废墟
    }

    public destroy(): void {
        this.active = false;
    }
}
